package com.sgcc.pda.mdrh.task.safe.ui.ac;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.sgcc.pda.baselibrary.utils.ToastUtils;
import com.sgcc.pda.mdrh.task.safe.R;
import com.sgcc.pda.mdrh.utils.AppManagerUtil;

/**
 * 描述：用于展示页面跳转认证提示
 * 作者：jianiuqi 2020-09-16 14:05
 */
public class SafeTipDialogActivity extends FragmentActivity {

    public static final String SAFE_VERITY_MESSAGE = "safe_verity_message";
    public static final String SAFE_VERITY_OPEN_URL = "safe_verity_open_url";
    public static final String SAFE_VERIFY_SHOW_CANCEL = "safe_verify_show_cancel";

    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;

    //倒计时
    TextView tvTime;
    //提示信息
    TextView tvMessage;
    //要跳转的页面
    String mWebUrl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.SafeTipDialogTheme);
        setContentView(R.layout.activity_safe_tip_dialog);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        //ImageView动画
        ImageView ivProgress = findViewById(R.id.iv_progress);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_rotate_repeat);
        animation.setInterpolator(new LinearInterpolator());
        ivProgress.startAnimation(animation);
        tvTime = findViewById(R.id.tv_time);
        //数据接收
        String message = getIntent().getStringExtra(SAFE_VERITY_MESSAGE);
        mWebUrl = getIntent().getStringExtra(SAFE_VERITY_OPEN_URL);
        boolean showCancel = intent.getBooleanExtra(SAFE_VERIFY_SHOW_CANCEL, true);
        tvMessage = findViewById(R.id.tv_msg);
        Button btnCancel = findViewById(R.id.btn_cancel);

        tvMessage.setText(message);
        if (!showCancel) {
            btnCancel.setVisibility(View.GONE);
        } else {
            btnCancel.setVisibility(View.VISIBLE);
            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        // 点击确定打开页面或者关闭
        findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openWebActivity();
                finish();
            }
        });
        mTimer.start();
    }

    CountDownTimer mTimer = new CountDownTimer(10 * 1000, 1000) {
        public void onTick(long millisUntilFinished) {
            SpannableString spannableString = new SpannableString("倒计时 " + millisUntilFinished / 1000 + " 秒");
            spannableString.setSpan(new ForegroundColorSpan(Color.RED), spannableString.length() - 3, spannableString.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvTime.setText(spannableString);
        }

        public void onFinish() {
            openWebActivity();
            finish();
        }
    };

    /**
     * 打开WebView
     */
    private void openWebActivity() {
        if (!TextUtils.isEmpty(mWebUrl)) {
            //判断是否有读写权限
            if (!checkPermission()) {
                return;
            }
            //判断应用是否安装
            if (!checkAppInstall()) {
                return;
            }
            Intent intent = new Intent(getApplicationContext(), MixWebViewActivity.class);
            intent.putExtra("webUrl", mWebUrl);
            startActivity(intent);
        }
    }

    /**
     * 判断是否有文件读写权限
     */
    private boolean checkPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
                ToastUtils.show(this, "请先开启文件读写权限");
                return false;
            }
        }
        return true;
    }

    /**
     * 判断应用是否安装
     */
    private boolean checkAppInstall() {
        if (mWebUrl.contains(getString(R.string.work_plan_pkg))) { //作业计划
            boolean isInstalled = AppManagerUtil.getInstance().isAppInstalled(this, getString(R.string.work_plan_pkg));
            if (!isInstalled) {
                ToastUtils.show(this, getString(R.string.work_plan_no_install));
                return false;
            }
        } else if (mWebUrl.contains(getString(R.string.ticket_pkg))) { //工作票
            boolean isInstalled = AppManagerUtil.getInstance().isAppInstalled(this, getString(R.string.ticket_pkg));
            if (!isInstalled) {
                ToastUtils.show(this, getString(R.string.ticket_no_install));
                return false;
            }
        } else if (mWebUrl.contains(getString(R.string.meeting_pkg))) { //班前会
            boolean isInstalled = AppManagerUtil.getInstance().isAppInstalled(this, getString(R.string.meeting_pkg));
            if (!isInstalled) {
                ToastUtils.show(this, getString(R.string.meeting_no_install));
                return false;
            }
        } else if (mWebUrl.contains(getString(R.string.knowledge_pkg))) { //知识库
            boolean isInstalled = AppManagerUtil.getInstance().isAppInstalled(this, getString(R.string.knowledge_pkg));
            if (!isInstalled) {
                ToastUtils.show(this, getString(R.string.knowledge_no_install));
                return false;
            }
        } else if (mWebUrl.contains(getString(R.string.risk_pkg))) { //风险点
            boolean isInstalled = AppManagerUtil.getInstance().isAppInstalled(this, getString(R.string.risk_pkg));
            if (!isInstalled) {
                ToastUtils.show(this, getString(R.string.risk_no_install));
                return false;
            }
        } else if (mWebUrl.contains(getString(R.string.work_task_pkg))) { //任务发起
            boolean isInstalled = AppManagerUtil.getInstance().isAppInstalled(this, getString(R.string.work_task_pkg));
            if (!isInstalled) {
                ToastUtils.show(this, getString(R.string.work_task_no_install));
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permissions[i])) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        openWebActivity();
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
        }
    }
}
